package com.mahjong.server.manager;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import com.mahjong.server.common.EmRoomStatus;
import com.mahjong.server.mina.protocol.AbsMessageProtocol;
import com.mahjong.server.model.Player;
import com.mahjong.server.model.Room;

/**
 * 游戏管理
 * 
 * @author Simple
 * @date 2013-4-3 下午03:55:04
 * @Description TODO
 */
@Component
public class RoomManager implements InitializingBean {

	private Logger log = Logger.getLogger(this.getClass());

	// 房间id
	private static int roomId;

	// 所有房间列表
	public static List<Room> rooms = new LinkedList<Room>();

	// id-Room
	public static Map<Integer, Room> id2room = new ConcurrentHashMap<Integer, Room>();

	/**
	 * 初始化房间
	 */
	public void initRooms() {
		log.debug("init ROOMS");
		for (int i = 0; i < 50; i++) {
			Room room = createRoom();
			rooms.add(room);
			id2room.put(room.getId(), room);
		}
	}

	/**
	 * 创建房间
	 * 
	 * @return
	 */
	private Room createRoom() {
		Room room = new Room(roomId++);
		room.setName("computer" + (roomId + 1));
		room.setStatus(EmRoomStatus.WAITING);
		room.setTotalCount(4);
		return room;
	}

	/**
	 * 删除房间
	 */
	public void removeRoom(Room room) {
		rooms.remove(room);
	}

	/**
	 * 获得所有房间
	 * 
	 * @return
	 */
	public List<Room> getAllRoom() {
		return rooms;
	}

	/**
	 * 当本类被Spring注入成组件后开始执行此方法，用来初始化房间
	 */
	public void afterPropertiesSet() throws Exception {
		initRooms();
	}

	/**
	 * 测试方法
	 * 
	 * @param size
	 * @return
	 */
	public List<Room> testGetRooms(int size) {
		List<Room> temp = new LinkedList<Room>();
		for (int i = 0; i < size; i++) {
			temp.add(rooms.get(i));
		}
		return temp;
	}

	/**
	 * 通过id获得Room对象
	 * 
	 * @param id
	 * @return
	 */
	public Room getRoomById(int id) {
		return id2room.get(id);
	}

	/**
	 * 快速加入房间
	 * 
	 * @param p
	 * @return
	 */
	public Room quickEnterRoom(Player p) {
		for (Room room : rooms) {
			if (room.getStatus() == EmRoomStatus.WAITING) {// 有空闲房间
				if (room.addPlayer(p)) {// 加入玩家
					return room;
				}
			} else {// 没有空闲房间
				Room newRoom = createRoom();
				rooms.add(newRoom);
				if (newRoom.addPlayer(p)) {
					return newRoom;
				}
			}
		}
		return null;
	}

	/**
	 * 发送信息至除自己以外的其他玩家
	 * 
	 * @param me
	 * @param room
	 * @param message
	 */
	public void sendMessageToRoomOtherPlayer(Player me, Room room,
			AbsMessageProtocol message) {
		List<Player> players = room.getPlayers();
		for (Player p : players) {
			if (p != me) {
				p.getSession().write(message);
			}
		}
	}
}
